package http.secure.common.keys.validator.impl;

import http.secure.common.constant.SecureProperties;
import http.secure.common.keys.validator.RepeatValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;

/**
 * 基于Redis实现的重复请求验证器
 *
 * @see RedisTemplate
 */
@Slf4j
public record RedisRepeatValidator(ValueOperations<String, String> operations,
                                   SecureProperties properties) implements RepeatValidator {
    public RedisRepeatValidator(StringRedisTemplate template, SecureProperties properties) {
        this(template.opsForValue(), properties);
    }

    @Override
    public boolean isRepeated(long timestamp, String sign) {
        String key = "SECURE_" + sign;
        int linkValidTime = properties.getLinkValidTime();
        Boolean absent = operations.setIfAbsent(key, String.valueOf(timestamp), linkValidTime, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(absent);
    }
}
